import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserEntity } from './entities/user.entity';
import { Repository } from 'typeorm';
import * as CryptoJS from 'crypto-js';

@Injectable()
export class UserService {
  constructor(
    @Inject('USER_REPOSITORY') //注入用户数据库依赖
    private readonly userRepository: Repository<UserEntity>,
  ) {} // 注入用户表
  async create(createUserDto: CreateUserDto) {
    const user = this.userRepository.create(createUserDto);
    return this.userRepository.save(user);
  }
  async findAll() {
    const data = await this.userRepository.find();
    return data;
  }

  findOne(id: number) {
    return this.userRepository.findOne({
      where: { id },
    });
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    console.log(updateUserDto);

    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }

  async validate(username: string, password: string) {
    const md5P = CryptoJS.MD5(password).toString();
    const result = await this.userRepository.findOne({
      where: {
        username: username,
        password: md5P,
      },
    });
    return result;
  }
}
